import NavBar from '@/components/NavBar'
import {
  getUserProfile,
  updateProfile,
  uploadPhoto,
} from '@/store/actions/profile'
import { DatePicker, List, Drawer, Toast, Modal } from 'antd-mobile-v2'
import { useEffect, useState, useRef } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import styles from './index.module.scss'
import EditInput from './components/EditInput'
import EditList from './components/EditList'
import { logout } from '@/store/actions/login'
import { useHistory } from 'react-router'

const ProfileEdit = () => {
  const dispatch = useDispatch()
  const profile = useSelector((state) => state.profile.profile)
  const photoRef = useRef(null)
  const history = useHistory()

  useEffect(() => {
    dispatch(getUserProfile())
  }, [dispatch])

  // 控制抽屉1 昵称 简介
  const [inputOpen, setInputOpen] = useState({
    visible: false,
    type: '',
  })
  // 控制抽屉2 性别 头像
  const [listOpen, setListOpen] = useState({
    visible: false,
    type: '',
  })

  const onInputClose = () => {
    setInputOpen({
      visible: false,
      type: '',
    })
  }
  const onListClose = () => {
    setListOpen({
      visible: false,
      type: '',
    })
  }

  // 处理提交的通用方法
  const handleSubmit = async (type, value) => {
    await dispatch(updateProfile({ [type]: value }))
    Toast.success('更新成功')
    onInputClose()
  }

  // 抽屉2的配置项
  const config = {
    photo: [
      {
        title: '拍照',
        onClick: () => {
          photoRef.current.click()
        },
      },
      {
        title: '本地选择',
        onClick: () => {
          photoRef.current.click()
        },
      },
    ],
    gender: [
      {
        title: '男',
        onClick: async () => {
          await dispatch(updateProfile({ gender: 0 }))
          Toast.success('更新成功')
          onListClose()
        },
      },
      {
        title: '女',
        onClick: async () => {
          await dispatch(updateProfile({ gender: 1 }))
          Toast.success('更新成功')
          onListClose()
        },
      },
    ],
  }

  // 处理头像选择
  const handleFileChange = async (e) => {
    const file = e.target.files[0]
    const formData = new FormData()
    formData.append('photo', file)
    await dispatch(uploadPhoto(formData))
    Toast.success('上传成功')
    onListClose()
  }

  // 处理日期选择
  const handleTimeChange = async (date) => {
    const y = date.getFullYear()
    const m = date.getMonth() + 1
    const d = date.getDate()
    const str = `${y}-${m}-${d}`
    await dispatch(updateProfile({ birthday: str }))
    Toast.success('修改成功')
  }

  // 处理退出
  const handleLogout = () => {
    // 页面
    // - 0. 添加一个弹框
    // action操作
    // - 1. 清除本地token
    // - 2. 清除redux中的token
    Modal.alert('温馨提示', '你确认要进行退出操作么', [
      { text: '取消' },
      {
        text: '确定',
        style: { color: 'red' },
        onPress: () => {
          dispatch(logout())
          history.replace('/login')
        },
      },
    ])
  }

  return (
    <div className={styles.root}>
      {/* 页面内容部分分离 */}
      <div className="content">
        {/* 顶部导航栏 */}
        <NavBar>个人信息</NavBar>

        <div className="wrapper">
          {/* 列表一：显示头像、昵称、简介 */}
          <List className="profile-list">
            <List.Item
              arrow="horizontal"
              onClick={() => setListOpen({ visible: true, type: 'photo' })}
              extra={
                <span className="avatar-wrapper">
                  <img src={profile.photo} alt="" />
                </span>
              }
            >
              头像
            </List.Item>

            <List.Item
              arrow="horizontal"
              extra={profile.name}
              onClick={() =>
                setInputOpen({
                  visible: true,
                  type: 'name',
                })
              }
            >
              昵称
            </List.Item>

            <List.Item
              arrow="horizontal"
              onClick={() =>
                setInputOpen({
                  visible: true,
                  type: 'intro',
                })
              }
              extra={
                <span className="intro">
                  {profile.intro ? profile.intro : '未填写'}
                </span>
              }
            >
              简介
            </List.Item>
          </List>

          {/* 列表二：显示性别、生日 */}
          <List className="profile-list">
            <List.Item
              arrow="horizontal"
              extra={profile.gender === 0 ? '男' : '女'}
              onClick={() => setListOpen({ visible: true, type: 'gender' })}
            >
              性别
            </List.Item>

            <DatePicker
              mode="date"
              title="选择年月日"
              value={new Date(profile.birthday)}
              minDate={new Date(1900, 1, 1, 0, 0, 0)}
              maxDate={new Date()}
              onChange={handleTimeChange}
            >
              <List.Item arrow="horizontal" extra={profile.birthday}>
                生日
              </List.Item>
            </DatePicker>
          </List>

          {/* 文件选择框，用于头像图片的上传 */}
          <input
            type="file"
            ref={photoRef}
            onChange={handleFileChange}
            hidden
          />
        </div>

        {/* 底部栏：退出登录按钮 */}
        <div className="logout">
          <button className="btn" onClick={handleLogout}>
            退出登录
          </button>
        </div>
      </div>

      {/* 昵称 和 介绍的 抽屉 */}
      <Drawer
        className="drawer"
        sidebar={
          inputOpen.visible && (
            <EditInput
              onClose={onInputClose}
              onSubmit={handleSubmit}
              type={inputOpen.type}
            />
          )
        }
        position="right"
        open={inputOpen.visible}
        children={''}
      ></Drawer>

      {/* 头像 和 性别的 抽屉2 */}
      <Drawer
        sidebar={
          listOpen.visible && (
            <EditList
              type={listOpen.type}
              config={config}
              onClose={onListClose}
            />
          )
        }
        onOpenChange={onListClose}
        className="drawer-list"
        position="bottom"
        open={listOpen.visible}
        children={''}
      ></Drawer>
    </div>
  )
}

export default ProfileEdit
